const app = getApp()
const db = wx.cloud.database();

let postid = null;
let postindex = null;
let years = null;
let month = null;
let day = null;
let hours = null;
let minute = null;
let second = null;
Page({
  judgeOpenid(){
    db.collection("userInfo").where({
      _openid: app.currentUserOpenid, 
    }).get().then(res=>{
        // 获取当前用户的个人信息：头像、昵称、openid等
        this.setData({
          UserGameInfo: res.data[0]
        })
        // console.log("this.data.UserGameInfo",this.data.UserGameInfo);
        if (res.data.length !=0) {
          app.collectionOpenid = true
          console.log("云数据库有当前用户信息，允许用户进入社区页面");
          wx.switchTab({
            url: '../community/community',
          })
        }
        if(!app.collectionOpenid){
          console.log("用户未授权登录，退回授权页面");
          wx.redirectTo({
          url: '../authorization/authorization',
          })
        }
    })
  },

  getUserOpenId(){
    wx.cloud.callFunction({
      name: 'getOpenId',
      complete: res => {
        app.currentUserOpenid = res.result.openid

        wx.cloud.callFunction({
          name: 'getPost',
        }).then(res2 => {
          let tempImgArr = []
          res2.result.data.forEach(
            (item,index)=>{
              tempImgArr.push(item)
            }
          )
          this.setData({
            wdfImgArr: tempImgArr
          })
          // console.log("wdfImgArr 用来渲染",this.data.wdfImgArr[0].comments);
        })
        .catch(console.error)
      }
    })
  },

  //清除历史记录
  cleanhistory: function (e) {
    this.setData({
      history: false, //隐藏历史记录
      historyArray: [], //清空历史记录数组
      newArray: [],
      shoopingtext: "" //清空搜索框
    })
  },
  //搜索
  search: function (e) {
    let searchtext = this.data.shoopingtext; //搜索框的值
    let sss = true;
    if (searchtext != "") {
      //将搜索框的值赋给历史数组
      this.data.historyArray.push(searchtext);
      //模糊查询 循环查询数组中的title字段
      for (let index in this.data.shoopingarray) {
        let num = this.data.shoopingarray[index].title.indexOf(searchtext);
        let temp = 'shoopingarray[' + index + '].status';
        if (num != -1) { //不匹配的不显示
          this.setData({
            [temp]: 1,
          })
          sss = false //隐藏未找到提示
        }
      }
      this.setData({
        history: false, //隐藏历史记录
        noneview: sss, //隐藏未找到提示
        shoppinglist: true, //显示商品列表
        newArray: this.data.historyArray //给新历史记录数组赋值
      })
    } else {
      this.setData({
        noneview: true, //显示未找到提示
        shoppinglist: false, //隐藏商品列表
        history: false, //隐藏历史记录
      })
    }
  },

  onPullDownRefresh() {
    this.onShow();
    console.log("上拉刷新");
    wx.showNavigationBarLoading() //在标题栏中显示加载

  },

  img: function () {
    wx.navigateTo({
      url: '../img/img'
    })
  },
  getUserInfo: function (e) {
    console.log(e.detail.userInfo)
    wx.request({
      url: app.globalData.url + 'all',
      data: {
        'writer': e.detail.userInfo.nickName,
        'pic': e.detail.userInfo.avatarUrl,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log('submit successs');
        },
        fail: function (res) {
          console.log('submit fail');
        }
      }
    })
  },
  formSubmit(e) {
    console.log(e.detail.value)
    wx.navigateTo({
      url: '../find/find?find=' + e.detail.value.find, 
    })
  },

  data: {
    // 帖子/动态区
    UserGameInfo: {},
    wdfImgArr: [],
    openOrClose: false,
    comments: [],

    // 以下是搜索框的
    newscode: '',
    newsresult: [],
    shoopingtext: "", //搜索框的值
    history: false, //显示历史记录
    noneview: false, //显示未找到提示
    shoppinglist: false, //显示商品列表
    historyArray: [], //历史记录数组,
    newArray: [], //添加历史记录数组
    shoopingarray: [{ //搜索资源
      id: 0,
      images: "https://tse3-mm.cn.bing.net/th/id/OIP-C.fsLgRUa-dxvrbS8rX4FWSwHaEK?w=273&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7",
      title: "不求人带队夺冠，用实力来回击质疑...",
    }, {
      id: 1,
      images: "https://tse4-mm.cn.bing.net/th/id/OIP-C.EjkRTATWtUn7_su1y7uOQgHaEo?w=269&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7",
      title: "主播鲨鱼造就“锁猴塔”，好一手战术伏地...",
    }, {
      id: 2,
      images: "https://shp.qpic.cn/cfwebcap/0/e6a9d7154e5dfe1f45f8834848311573/0/?width=740&height=650",
      title: "童话森林套装限时返场...",
    },{
      id: 3,
      images: "https://shp.qpic.cn/cfwebcap/0/5e7089457f14127ae99c4df543b3acae/0/?width=485&height=470",
      title: "童话森林系列的头盔、背包、挂件、降落伞、碎片手雷...",
    },{
      id: 4,
      images: "https://tse3-mm.cn.bing.net/th/id/OIP-C.6q5Hn0cE-x2cHpRxjzh2kQHaEH?w=324&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7",
      title: "五指狙神晚玉防空洞堵人，赶尽杀绝...",
    },{
      id: 5,
      images: "https://shp.qpic.cn/cfwebcap/0/4c4f0d2b864ac98177e94d869a34931b/0/?width=750&height=400",
      title: "【免费福利】直男必备表情包来袭",
    },{
      id: 6,
      images: "https://tse1-mm.cn.bing.net/th/id/OIP-C.w4TTbCJkH0g5JqqnP9CvqwHaC-?w=310&h=140&c=7&r=0&o=5&dpr=1.25&pid=1.7",
      title: "由于钢琴花园，网友玩起了“彩虹”夸策划小白裙...",
    },{
      id: 7,
      images: "https://shp.qpic.cn/cfwebcap/0/50ed4be84a0cbd0e186f4114d8855aad/0/?width=5560&height=3127",
      title: "光子鸡小队登场！《和平精英》3周年，你的加油鸡到了！",
    },{
      id: 8,
      images: "https://shp.qpic.cn/cfwebcap/0/4c4f0d2b864ac98177e94d869a34931b/0/?width=750&height=400",
      title: "光子战术竞技游戏推荐官登场，光子鸡小队闪亮首秀！",
    },{
      id: 9,
      images: "https://shp.qpic.cn/cfwebcap/0/0869f1a7f1dad938c9ab2f44b3f25ada/0/?width=4370&height=1940",
      title: "由于钢琴花园，网友玩起了“彩虹”夸策划小白裙...",
    },{
      id: 10,
      images: "https://shp.qpic.cn/cfwebcap/0/53eb7b7290ced079b19bdca1c82228ad/0?width=554&height=366",
      title: "上快手直播，看童家堡阵营大作战！！",
    },{
      id: 11,
      images: "https://shp.qpic.cn/cfwebcap/0/800f95a7775bab1855a68b54f66a2ac7/0?width=554&height=370",
      title: "上快手和B站搜索“王小歪大战难言”，观全新阵营玩法！",
    },{
      id: 12,
      images: "https://shp.qpic.cn/cfwebcap/0/f45a91a0b61d7bf8ad5130b3f646a8ce/0/?width=750&height=400",
      title: "免费获取3周年庆福利 | 光子鸡和平精英篇表情包",
    },{
      id: 13,
      images: "https://tse1-mm.cn.bing.net/th/id/OIP-C.BXZScafDTrGbP3WIz3NNHgHaEK?w=313&h=180&c=7&r=0&o=5&dpr=1.75&pid=1.7",
      title: "不求人这“猛男”语音包，真香警告！！！",
    },{
      id: 14,
      images: "https://tse1-mm.cn.bing.net/th/id/OIP-C.Wd2_wf6f8_hbReFZsxzgpQAAAA?w=232&h=171&c=7&r=0&o=5&dpr=1.75&pid=1.7",
      title: "王一博和不求人，在海岛联手出击，大战粉丝！",
    },{
      id: 15,
      images: "https://tse3-mm.cn.bing.net/th/id/OIP-C.tHsoH42nZIbdjJeqL7XKkwHaEK?w=315&h=180&c=7&r=0&o=5&dpr=1.75&pid=1.7",
      title: "虎牙明星主播不求人，竟把高端上分局完成粉丝见面会",
    }],
    lunbo2: [
      "https://game.gtimg.cn/images/gp/zlkdatasys/images/image/20220412/16497729229130.jpg", 
      "https://tse3-mm.cn.bing.net/th/id/OIP-C.fsLgRUa-dxvrbS8rX4FWSwHaEK?w=273&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7",
     "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.nbd.com.cn%2Fuploads%2Farticles%2Fimages%2F942003%2F6pic_hd.jpg&refer=http%3A%2F%2Fimage.nbd.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652008639&t=32ce371eaf0410d70c7e1d76b11f4829", 
     "https://tse4-mm.cn.bing.net/th/id/OIP-C.oPr_gxmt_BgArvHT4g0uBAHaEK?w=296&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7",
      "https://tse4-mm.cn.bing.net/th/id/OIP-C.EjkRTATWtUn7_su1y7uOQgHaEo?w=269&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7"
    ]
  },
  //搜索框的值
  shoppinginput: function (e) {
    //当删除input的值为空时
    if (e.detail.value == "") {
      this.setData({
        history: true, //显示历史记录
        shoppinglist: false //隐藏商品列表
      });
      //所有商品列表的状态改为0
      for (let index in this.data.shoopingarray) {
        let temp = 'shoopingarray[' + index + '].status';
        this.setData({
          [temp]: 0,
        })
      }
    }
    this.setData({
      shoopingtext: e.detail.value
    })
  },
  //点击历史记录赋值给搜索框
  textfz: function (e) {
    this.setData({
      shoopingtext: e.target.dataset.text
    })
  },

  onLoad: function (options) {

    // // 游戏资讯
    // let _this = this
    // wx.request({
    //   url: 'http://api.tianapi.com/esports/index',
    //   method: 'GET',
    //   data: {
    //     key: "27c57dac5e492988aa5fc95d92b3783a",
    //     num: "1"
    //   },
    //   success: function (res) {
    //     // console.log(res.data)
    //     _this.setData({
    //       newscode: res.data.code,
    //       newsresult: res.data.newslist
    //     })
    //   }
    // })

    // // 显示加载中
    // wx.showLoading({
    //   title: '加载中',
    // })
    // setTimeout(function () {
    //   wx.hideLoading()
    // }, 1000)
  },

  // 这个是点赞的点击事件,获取所点击动态的id和index
  getpostid(e){
    postid = e.currentTarget.dataset.id
    console.log("id=>",e.currentTarget.dataset.id);
    postindex = e.currentTarget.dataset.idx
    this.data.UserGameInfo.likes.forEach(
      (item,index) => {
        if (item == postid) {
          console.log("已经点过赞了，再点击则取消点赞 且-1");
          wx.cloud.callFunction({
            name: "getHits",
            data:{
              id: postid
            }
          }).then(res5=>{
            // console.log(res5.result.data.hits);
            let tempHits = res5.result.data.hits
            tempHits -= 1
            wx.cloud.callFunction({
              name: "updateLiked",
              data:{
                id: postid,
                tempHits
              }
            }).then(res8=>{
              let tempDate = this.data.wdfImgArr
              tempDate[postindex].hits -= 1;
              this.setData({
                wdfImgArr: tempDate
              })
            })
          })
          this.setData({
            like: "block",
            liked: "none"
          })

        }else if(index == this.data.UserGameInfo.likes.length - 1){
          console.log("首次点赞，+1");
          wx.cloud.callFunction({
            name: "updateLikes",
            data:{
              id: postid,
            }
          }).then(res=>{
            let tempDate = this.data.wdfImgArr
            tempDate[postindex].hits += 1;
            this.setData({
              wdfImgArr: tempDate
            })
          })
          let tempLiksArr = this.data.UserGameInfo.likes
          tempLiksArr.push(postid)
          db.collection("userInfo").doc(this.data.UserGameInfo._id).update({
            data:{
              likes: tempLiksArr
            }
          }).then(res3=>{
            this.setData({
              liked: "block",
              like: "none"
            })
          })
        }
      }
    )
  },

  /**
   * 生命周期函数--监听页面显示
  */
  onShow: function () {
    // 调用查询用户openid的函数
    this.getUserOpenId()
    // 调用判断用户openid和集合里的openid是否相符
    this.judgeOpenid()
  },

  // 打开评论区————————————————————————————————————————————
  openComment(e){
    // console.log(e.currentTarget.dataset.id);
    let id = e.currentTarget.dataset.id
    if (this.data.openOrClose == false) {
      wx.cloud.callFunction({
        name: "getPostByid",
        data:{
          id,
        }
      }).then(res2=>{
        this.setData({
          commentBox: "block",
          openOrClose: true,
          borderBottom: "6rpx solid red;",
          comments: res2.result.data.comments
        })
        this.onLoad()
        // console.log("this.data.comments",this.data.comments);
      })
    }else {
      this.setData({
        commentBox: "none",
        openOrClose: false,
        borderBottom: "none"
      })
    }
    this.onLoad()
  },

  getNowTime(){
    let NowTime = new Date()
    years = NowTime.getFullYear()
    month = NowTime.getMonth() + 1
    day = NowTime.getDate()
    hours = NowTime.getHours()
    minute = NowTime.getMinutes()
    second = NowTime.getSeconds()
    return `${years}-${month}-${day} ${hours}:${minute}:${second}`
  },

  commentSubmit(res){
    // console.log("currentTarget",res.detail.target.dataset); // 当前帖子ID和index
    // console.log("currentTarget.commentCon",res.detail.value.commentCon); // input 值
    if (res.detail.value.commentCon) {
      let id = res.detail.target.dataset.id
      let {avatarUrl,nickName} = this.data.UserGameInfo
      let stageText = this.data.UserGameInfo.stage.stageText
      let tempObject = {
        avatarUrl,  // 头像
        nickName,  // 昵称
        stageText, // 段位
        CommentTime: this.getNowTime(), //发表时间
        comTextInp: res.detail.value.commentCon, // input值
        comments: [],
      }
      wx.cloud.callFunction({
        name: "getPostByid",
        data:{
          id,
        }
      }).then(res2=>{
        let tempComments = res2.result.data.comments
        tempComments.push(tempObject)
        let tempComNum = tempComments.length
        wx.cloud.callFunction({
          name: "updatePost",
          data:{
            id,
            tempComments,
            tempComNum,
          }
        })
        this.setData({
          conText: '',
          comments: tempComments
        })
        this.onLoad()
        // console.log("this.data.comments",this.data.comments);
      })
    }else {
      wx.showToast({
        title: '请别空着！',
        icon: "error"
      })
    }
  },

  // 置顶按钮
  zhiding() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  publish(){
    wx.redirectTo({
      url: '../../pages/publishPost/publishPost',
    })
  },

  nav: function () {
    wx.redirectTo({
      url: '../../pages/more/more',
    })
  },
})